''' 
@文件：5.使用协程拉取王者荣耀英雄皮肤图片.py
@作者：Miss丶念
@时间：2025/3/23：11:08
'''

import os
import asyncio
import aiohttp
import aiofile  # aiofile为异步文件操作库，不会阻塞事件循环


class HeroSkinDownloader:
    def __init__(self):
        self.json_url = 'https://pvp.qq.com/web201605/js/herolist.json'
        self.skin_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{}/{}-bigskin-{}.jpg'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.54',
        }

    async def get_data_content(self, session, e_name, c_name):
        for skin_id in range(1, 31):
            async with session.get(self.skin_url.format(e_name, e_name, skin_id), headers=self.headers) as response:
                if response.status == 200:
                    content = await response.read()
                    async with aiofile.async_open('./img/' + c_name + '-' + str(skin_id)+'.jpg', 'wb') as f:
                        await f.write(content)
                        print(f'{c_name}-{skin_id}下载完成')
                else:
                    break

    async def main(self):
        task_list = list()
        async with aiohttp.ClientSession() as session:
            async with session.get(self.json_url, headers=self.headers) as response:
                # 获取json数据,content_type=None 是避免报错
                result = await response.json(content_type=None)
                for itme in result:
                    ename = itme['ename']
                    cname = itme['cname']
                    task = self.get_data_content(session, ename, cname )
                    task_list.append(asyncio.create_task(task))
                await asyncio.wait(task_list)


if __name__ == '__main__':
    if not os.path.exists('./img'):
        os.mkdir('./img')
        print('创建文件夹成功')
    hero_skin = HeroSkinDownloader()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(hero_skin.main())
